package net.lmc.realtime.jtp.dwd.log.function;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import net.lmc.bwie.realtime.jtp.common.utils.DateTimeUtil;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

/**
 * 使用状态State编程，对is_new字段值进行校验和纠偏
 * @author xuanyu
 */
public class AdjustIsNewProcessFunction extends KeyedProcessFunction<String, String, String> {

     //声明状态
    private transient ValueState<String> firstDateState = null ;

    @Override
    public void open(Configuration parameters) throws Exception {

        //初始化状态

        firstDateState = getRuntimeContext().getState(
                new ValueStateDescriptor<String>("firstDate", String.class)
        );
    }

    @Override
    public void processElement(String value,
                               KeyedProcessFunction<String, String, String>.Context ctx,
                               Collector<String> out) throws Exception {

         //获取状态值
        String firstDate = firstDateState.value();

        // 获取ts和isNew字段值
        JSONObject jsonObject = JSON.parseObject(value);
        Long tsValue = jsonObject.getLong("ts");
        String isNewValue = jsonObject.getJSONObject("common").getString("is_new");
        /*
       firstDate = null 并且 isNewValue = 1 新访客 正常，设置firstDate为当前日期
          isNewValue = 0 老访客 正常，设置firstDate给一个日期值，比如昨天日期

       firstDate 有值情况 并且 isNewValue = 1 新访客
             firstDate = ts中日期，不变
             firstDate != ts中日期，纠偏修改is_new值为0
       */
        if("1".equals(isNewValue)){
            if (null == firstDate){
                firstDateState.update(DateTimeUtil.convertLongToString(tsValue,DateTimeUtil.DATE_FORMAT));
            }else{
                if(!firstDate.equals(DateTimeUtil.convertLongToString(tsValue,DateTimeUtil.DATE_FORMAT))){
                    jsonObject.getJSONObject("common").put("is_new","0");
                }
            }
        }else{
            if(null == firstDate){
                firstDateState.update(DateTimeUtil.convertLongToString(tsValue - 86400000,DateTimeUtil.DATE_FORMAT));
            }
        }

        // 输出
        out.collect(jsonObject.toJSONString());
    }

    @Override
    public void close() throws Exception {
        super.close();
    }

}